package com.swu.service.impl;

import com.swu.service.IAIService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AIServiceImpl implements IAIService {

    private final ChatClient chatClient;

    @Override
    public String generateDroolsRule(String ruleName, String ruleDescription) {
        String prompt = """
                你是一个医疗病案首页校验规则生成专家，请根据以下信息生成Drools规则：
                            
                规则名称：%s
                规则描述：%s
                            
                可用的实体类和字段信息：
                            
                1. PatientInfo - 患者基本信息
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import java.time.LocalDate;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import java.io.Serializable;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        /**
                         * <p>
                         * 患者基本信息表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("patient_info")
                        @Schema(name = "PatientInfo", description = "患者基本信息表")
                        public class PatientInfo implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "病案号")
                            @TableId(value = "medical_record_id", type = IdType.AUTO)
                            private String medicalRecordId;
                        
                            @Schema(description = "健康卡号")
                            private String healthCard;
                        
                            @Schema(description = "姓名")
                            private String name;
                        
                            @Schema(description = "性别")
                            private String gender;
                        
                            @Schema(description = "出生日期")
                            private LocalDate birthDate;
                        
                            @Schema(description = "年龄")
                            private Integer age;
                        
                            @Schema(description = "婴儿月龄")
                            private Integer infantAgeMonths;
                        
                            @Schema(description = "国籍")
                            private String nationality;
                        
                            @Schema(description = "出生地")
                            private String birthPlace;
                        
                            @Schema(description = "籍贯")
                            private String originPlace;
                        
                            @Schema(description = "民族")
                            private String ethnicity;
                        
                            @Schema(description = "证件号码")
                            private String idNumber;
                        
                            @Schema(description = "职业")
                            private String occupation;
                        
                            @Schema(description = "婚姻状况：1.未婚 2.已婚 3.丧偶 4.离婚 9.其他")
                            private Integer maritalStatus;
                        
                            @Schema(description = "现住址")
                            private String currentAddress;
                        
                            @Schema(description = "电话")
                            private String phone;
                        
                            @Schema(description = "邮编")
                            private String postalCode;
                        
                            @Schema(description = "户口地址")
                            private String registeredAddress;
                        
                            @Schema(description = "工作单位及地址")
                            private String workUnit;
                        
                            @Schema(description = "单位电话")
                            private String workPhone;
                        
                            @Schema(description = "联系人姓名")
                            private String contactName;
                        
                            @Schema(description = "联系人关系")
                            private String contactRelation;
                        
                            @Schema(description = "联系人电话")
                            private String contactPhone;
                        
                            @Schema(description = "血型：1.A 2.B 3.O 4.AB 5.不详 6.未查")
                            private Integer bloodType;
                        
                            @Schema(description = "Rh因子：1.阴 2.阳 3.不详 4.未查")
                            private Integer rhFactor;
                        
                            @Schema(description = "损伤中毒外部原因")
                            private String injuryCause;
                        
                            @Schema(description = "就治医院编码")
                            private String facilityOrgCode;
                        }
                           
                2. AdmissionInfo - 住院信息
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        import java.io.Serializable;
                        import java.time.LocalDateTime;
                        
                        /**
                         * <p>
                         * 住院信息表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("admission_info")
                        @Schema(description="住院信息表")
                        public class AdmissionInfo implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "住院标识")
                            @TableId(value = "admission_id", type = IdType.AUTO)
                            private Integer admissionId;
                        
                            @Schema(description = "病案号")
                            private String medicalRecordId;
                        
                            @Schema(description = "第几次住院")
                            private Integer admissionCount;
                        
                            @Schema(description = "医疗付费方式：1.城镇职工基本医疗保险 2.城镇居民基本医疗保险 3.新型农村合作医疗 4.贫困求助 5.商业医疗保险 6.全公费 7.全自费 8.其他社区保险 9.其他")
                            private Integer paymentMethod;
                        
                            @Schema(description = "入院途径：1.急诊 2.门诊 3.其他医疗机构转入 9.其他")
                            private Integer admissionPath;
                        
                            @Schema(description = "入院时间")
                            private LocalDateTime admissionTime;
                        
                            @Schema(description = "入院科别")
                            private String admissionDept;
                        
                            @Schema(description = "病房")
                            private String ward;
                        
                            @Schema(description = "转科科别")
                            private String transferDept;
                        
                            @Schema(description = "出院时间")
                            private LocalDateTime dischargeTime;
                        
                            @Schema(description = "出院科别")
                            private String dischargeDept;
                        
                            @Schema(description = "实际住院天数")
                            private Integer actualDays;
                        
                            @Schema(description = "门(急)诊诊断")
                            private String erDiagnosis;
                        
                            @Schema(description = "门(急)诊疾病编码")
                            private String erDiagCode;
                        
                        
                        }
                        
                   
                3. BillingInfo - 费用信息
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        import java.io.Serializable;
                        import java.math.BigDecimal;
                        
                        /**
                         * <p>
                         * 费用信息表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("billing_info")
                        @Schema(name="BillingInfo对象", description="费用信息表")
                        public class BillingInfo implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "费用ID")
                            @TableId(value = "billing_id", type = IdType.AUTO)
                            private Integer billingId;
                        
                            @Schema(description = "病案号")
                            private String medicalRecordId;
                        
                            @Schema(description = "总费用(元)")
                            private BigDecimal totalCost;
                        
                            @Schema(description = "自付金额")
                            private BigDecimal selfPay;
                        
                            @Schema(description = "一般医疗服务费")
                            private BigDecimal generalMedicalService;
                        
                            @Schema(description = "一般治疗操作费")
                            private BigDecimal generalTreatmentOperation;
                        
                            @Schema(description = "护理费")
                            private BigDecimal nursingFee;
                        
                            @Schema(description = "其他费用")
                            private BigDecimal otherFee;
                        
                            @Schema(description = "病理诊断费")
                            private BigDecimal pathologyDiagnosis;
                        
                            @Schema(description = "实验室诊断费")
                            private BigDecimal laboratoryDiagnosis;
                        
                            @Schema(description = "影像学诊断费")
                            private BigDecimal imagingDiagnosis;
                        
                            @Schema(description = "临床诊断项目费")
                            private BigDecimal clinicalDiagnosis;
                        
                            @Schema(description = "非手术治疗项目费")
                            private BigDecimal nonSurgicalTreatment;
                        
                            @Schema(description = "手术治疗费")
                            private BigDecimal surgicalTreatment;
                        
                            @Schema(description = "康复费")
                            private BigDecimal rehabilitation;
                        
                            @Schema(description = "中医治疗费")
                            private BigDecimal tcmTreatment;
                        
                            @Schema(description = "西药费")
                            private BigDecimal westernMedicine;
                        
                            @Schema(description = "中成药费")
                            private BigDecimal chinesePatentMedicine;
                        
                            @Schema(description = "中草药费")
                            private BigDecimal chineseHerbalMedicine;
                        
                            @Schema(description = "血费")
                            private BigDecimal bloodFee;
                        
                            @Schema(description = "白蛋白类制品费")
                            private BigDecimal albumin;
                        
                            @Schema(description = "球蛋白类制品费")
                            private BigDecimal globulin;
                        
                            @Schema(description = "检查用一次性医用材料费")
                            private BigDecimal disposableExamMaterials;
                        
                            @Schema(description = "治疗用一次性医用材料费")
                            private BigDecimal disposableTreatMaterials;
                        
                            @Schema(description = "手术用一次性医用材料费")
                            private BigDecimal disposableSurgeryMaterials;
                        
                            @Schema(description = "其他费用")
                            private BigDecimal otherCosts;
                        
                        
                        }
                       
                   
                4. DiagnosisInfo - 诊断信息
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import java.io.Serializable;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        /**
                         * <p>
                         * 诊断信息表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("diagnosis_info")
                        @Schema(name = "DiagnosisInfo", description = "诊断信息表")
                        public class DiagnosisInfo implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "诊断ID")
                            @TableId(value = "diagnosis_id", type = IdType.AUTO)
                            private Integer diagnosisId;
                        
                            @Schema(description = "病案号")
                            private String medicalRecordId;
                        
                            @Schema(description = "诊断类型：1-主要诊断, 2-其他诊断, 3-病理诊断")
                            private Integer diagnosisType;
                        
                            @Schema(description = "诊断名称")
                            private String diagnosisName;
                        
                            @Schema(description = "疾病编码")
                            private String diagCode;
                        
                            @Schema(description = "入院病情：1-有/2-临床未确定/3-情况不明/4-无")
                            private Integer admissionStatus;
                        
                            @Schema(description = "病理号")
                            private String pathologyNumber;
                        
                        
                        }
                        
                   
                5. MedicalTeam - 医疗团队
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import java.time.LocalDate;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import java.io.Serializable;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        /**
                         * <p>
                         * 医疗团队与质控表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("medical_team")
                        @Schema(name = "MedicalTeam", description = "医疗团队与质控表")
                        public class MedicalTeam implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "团队ID")
                            @TableId(value = "team_id", type = IdType.AUTO)
                            private Integer teamId;
                        
                            @Schema(description = "病案号")
                            private String medicalRecordId;
                        
                            @Schema(description = "科主任")
                            private String departmentHead;
                        
                            @Schema(description = "主任(副主任)医师")
                            private String chiefPhysician;
                        
                            @Schema(description = "主治医师")
                            private String attending;
                        
                            @Schema(description = "住院医师")
                            private String resident;
                        
                            @Schema(description = "责任护士")
                            private String nurse;
                        
                            @Schema(description = "编码员")
                            private String coder;
                        
                            @Schema(description = "病案质量等级：1-甲,2-乙,3-丙")
                            private Integer qualityGrade;
                        
                            @Schema(description = "质控医师")
                            private String qcDoctor;
                        
                            @Schema(description = "质控护士")
                            private String qcNurse;
                        
                            @Schema(description = "质控日期")
                            private LocalDate qcDate;
                        
                        
                        }
                6. DischargeInfo 出院信息实体类
                        
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        import java.io.Serializable;
                        
                        /**
                         * <p>
                         * 出院信息表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("discharge_info")
                        @Schema(name="DischargeInfo对象", description="出院信息表")
                        public class DischargeInfo implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "出院ID")
                            @TableId(value = "discharge_id", type = IdType.AUTO)
                            private Integer dischargeId;
                        
                            @Schema(description = "病案号")
                            private String medicalRecordId;
                        
                            @Schema(description = "离院方式：1.医嘱离院 2.医嘱转院 3.医嘱转社区卫生服务机构/乡镇卫生院 4.非医嘱转院 5.死亡 9.其他")
                            private Integer dischargeMethod;
                        
                            @Schema(description = "拟接收机构")
                            private String receivingOrg;
                        
                            @Schema(description = "31天再住院计划：1-无,2-有")
                            private Integer readmissionPlan;
                        
                            @Schema(description = "再住院目的")
                            private String readmissionReason;
                        
                            @Schema(description = "入院前昏迷时间")
                            private String comaPre;
                        
                            @Schema(description = "入院后昏迷时间")
                            private String comaPost;
                        
                        
                        }
                
                7. FacilityInfo 医疗机构信息实体类
                
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import java.io.Serializable;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        /**
                         * <p>
                         * 医疗机构信息表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("facility_info")
                        @Schema(name = "FacilityInfo", description = "医疗机构信息表")
                        public class FacilityInfo implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "医疗机构名称")
                            private String orgName;
                        
                            @Schema(description = "组织机构编码")
                            @TableId(value = "org_code", type = IdType.AUTO)
                            private String orgCode;
                        
                        
                        }
                8. SurgeryInfo 手术信息实体类
                
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        import java.io.Serializable;
                        import java.time.LocalDate;
                        
                        /**
                         * <p>
                         * 手术操作表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("surgery_info")
                        @Schema(description="手术操作表")
                        public class SurgeryInfo implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "手术ID")
                            @TableId(value = "surgery_id", type = IdType.AUTO)
                            private Integer surgeryId;
                        
                            @Schema(description = "病案号")
                            private String medicalRecordId;
                        
                            @Schema(description = "手术操作编码")
                            private String surgeryCode;
                        
                            @Schema(description = "手术日期")
                            private LocalDate surgeryDate;
                        
                            @Schema(description = "手术操作名称")
                            private String surgeryName;
                        
                            @Schema(description = "手术级别：1-4级")
                            private Integer surgeryLevel;
                        
                            @Schema(description = "术者")
                            private String surgeon;
                        
                            @Schema(description = "第一助手")
                            private String assistant1;
                        
                            @Schema(description = "第二助手")
                            private String assistant2;
                        
                            @Schema(description = "切口愈合类别：0.0类切口 1.I类切口 2.Ⅱ类切口 3.III类切口")
                            private Integer healingGrade;
                        
                            @Schema(description = "麻醉方式")
                            private String anesthesiaType;
                        
                            @Schema(description = "麻醉医师")
                            private String anesthesiologist;
                        
                        
                        }
                
                
                9. ValidationRule 校验规则实体类
                        
                        package com.swu.po;
                        
                        import com.baomidou.mybatisplus.annotation.IdType;
                        import com.baomidou.mybatisplus.annotation.TableId;
                        import com.baomidou.mybatisplus.annotation.TableName;
                        import com.fasterxml.jackson.annotation.JsonFormat;
                        import io.swagger.v3.oas.annotations.media.Schema;
                        import lombok.Data;
                        import lombok.EqualsAndHashCode;
                        import lombok.experimental.Accessors;
                        
                        import java.io.Serializable;
                        import java.time.LocalDateTime;
                        
                        /**
                         * <p>
                         * 病案首页校验规则表
                         * </p>
                         *
                         * @author 勾新杰
                         * @since 2025-06-08
                         */
                        @Data
                        @EqualsAndHashCode(callSuper = false)
                        @Accessors(chain = true)
                        @TableName("validation_rule")
                        @Schema(name="ValidationRule对象", description="病案首页校验规则表")
                        public class ValidationRule implements Serializable {
                        
                            private static final long serialVersionUID = 1L;
                        
                            @Schema(description = "规则ID")
                            @TableId(value = "id", type = IdType.AUTO)
                            private Long id;
                        
                            @Schema(description = "规则名称")
                            private String ruleName;
                        
                            @Schema(description = "规则描述")
                            private String ruleDescription;
                        
                            @Schema(description = "规则类型：1-条件必填检查 2-逻辑一致性检查")
                            private Integer ruleType;
                        
                            @Schema(description = "规则内容（Drools规则语言）")
                            private String ruleContent;
                        
                            @Schema(description = "规则状态：0-禁用 1-启用")
                            private Integer status;
                        
                            @Schema(description = "创建时间")
                            @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                            private LocalDateTime createTime;
                        
                            @Schema(description = "更新时间")
                            @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                            private LocalDateTime updateTime;
                        
                            @Schema(description = "创建人，有默认值")
                            private String creator;
                        
                            @Schema(description = "更新人，有默认值")
                            private String updater;
                        
                        
                        }
                
                规则执行代码逻辑：
                
                        package com.swu.service;
                        
                        import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
                        import com.swu.po.*;
                        import com.swu.mapper.*;
                        import com.swu.common.Result;
                        import jakarta.annotation.PostConstruct;
                        import lombok.RequiredArgsConstructor;
                        import org.drools.core.impl.InternalKnowledgeBase;
                        import org.drools.core.impl.KnowledgeBaseFactory;
                        import org.kie.api.io.ResourceType;
                        import org.kie.internal.builder.KnowledgeBuilder;
                        import org.kie.internal.builder.KnowledgeBuilderFactory;
                        import org.kie.internal.io.ResourceFactory;
                        import org.springframework.stereotype.Service;
                        
                        import java.util.*;
                        
                        @Service
                        @RequiredArgsConstructor
                        public class MedicalRecordValidationService {
                            private final IValidationRuleService validationRuleService;
                            private final PatientInfoMapper patientInfoMapper;
                            private final DiagnosisInfoMapper diagnosisInfoMapper;
                            private final BillingInfoMapper billingInfoMapper;
                            private final MedicalTeamMapper medicalTeamMapper;
                            private final AdmissionInfoMapper admissionInfoMapper;
                            private final SurgeryInfoMapper surgeryInfoMapper;
                            private final DischargeInfoMapper dischargeInfoMapper;
                        
                            private InternalKnowledgeBase knowledgeBase;
                        
                            @PostConstruct
                            public void init() {
                                reloadRules();
                            }
                        
                            public void reloadRules() {
                                List<ValidationRule> rules = validationRuleService.list();
                                KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
                        
                                for (ValidationRule rule : rules) {
                                    if (rule.getStatus() == 1) {  // 只加载启用的规则
                                        builder.add(ResourceFactory.newByteArrayResource(rule.getRuleContent().getBytes()),
                                                ResourceType.DRL);
                                    }
                                }
                        
                                if (builder.hasErrors()) {
                                    throw new RuntimeException("规则编译错误: " + builder.getErrors());
                                }
                        
                                knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
                                knowledgeBase.addPackages(builder.getKnowledgePackages());
                            }
                        
                            public Result<List<String>> validate(String medicalRecordId) {
                                List<String> causes = new ArrayList<>();
                        
                                // 1. 检查必填关联表
                                checkRequiredTables(medicalRecordId, causes);
                        
                                // 如果必填表缺失，直接返回错误
                                if (!causes.isEmpty()) {
                                    return Result.error("数据校验失败", causes);
                                }
                        
                                executeRules(medicalRecordId, causes);
                        
                                return causes.isEmpty() ?
                                        Result.success(null) :
                                        Result.error("数据校验失败", causes);
                            }
                        
                            private void checkRequiredTables(String medicalRecordId, List<String> causes) {
                                // 检查患者基本信息
                                if (patientInfoMapper.selectById(medicalRecordId) == null) {
                                    causes.add("缺少患者基本信息数据");
                                }
                        
                                // 检查诊断信息
                                if (diagnosisInfoMapper.selectList(new LambdaQueryWrapper<DiagnosisInfo>().eq(DiagnosisInfo::getMedicalRecordId, medicalRecordId)).isEmpty()) {
                                    causes.add("缺少诊断信息数据");
                                }
                        
                                // 检查费用信息
                                if (billingInfoMapper.selectOne(new LambdaQueryWrapper<BillingInfo>().eq(BillingInfo::getMedicalRecordId, medicalRecordId)) == null) {
                                    causes.add("缺少费用信息表数据");
                                }
                        
                                // 检查医疗团队与质控表
                                if (medicalTeamMapper.selectOne(new LambdaQueryWrapper<MedicalTeam>().eq(MedicalTeam::getMedicalRecordId, medicalRecordId)) == null) {
                                    causes.add("缺少医疗团队与质控表数据");
                                }
                            }
                        
                            private void executeRules(String medicalRecordId, List<String> causes) {
                                // 准备规则引擎所需的数据
                                PatientInfo patientInfo = patientInfoMapper.selectById(medicalRecordId);
                                List<DiagnosisInfo> diagnosisList = diagnosisInfoMapper.selectList(
                                        new LambdaQueryWrapper<DiagnosisInfo>()
                                                .eq(DiagnosisInfo::getMedicalRecordId, medicalRecordId)
                                );
                                AdmissionInfo admissionInfo = admissionInfoMapper.selectOne(
                                        new LambdaQueryWrapper<AdmissionInfo>()
                                                .eq(AdmissionInfo::getMedicalRecordId, medicalRecordId)
                                );
                                SurgeryInfo surgeryInfo = surgeryInfoMapper.selectOne(
                                        new LambdaQueryWrapper<SurgeryInfo>()
                                                .eq(SurgeryInfo::getMedicalRecordId, medicalRecordId));
                                DischargeInfo dischargeInfo = dischargeInfoMapper.selectOne(
                                        new LambdaQueryWrapper<DischargeInfo>()
                                                .eq(DischargeInfo::getMedicalRecordId, medicalRecordId));
                                BillingInfo billingInfo = billingInfoMapper.selectOne(
                                        new LambdaQueryWrapper<BillingInfo>()
                                                .eq(BillingInfo::getMedicalRecordId, medicalRecordId));
                                MedicalTeam medicalTeam = medicalTeamMapper.selectOne(
                                        new LambdaQueryWrapper<MedicalTeam>()
                                                .eq(MedicalTeam::getMedicalRecordId, medicalRecordId));
                                // 创建会话并执行规则
                                org.kie.api.runtime.KieSession session = knowledgeBase.newKieSession();
                                try {
                                    session.setGlobal("causes", causes);
                                    session.insert(patientInfo);
                                    diagnosisList.forEach(session::insert);
                                    session.insert(admissionInfo);
                                    session.insert(surgeryInfo);
                                    session.insert(dischargeInfo);
                                    session.insert(billingInfo);
                                    session.insert(medicalTeam);
                                    session.fireAllRules();
                                } finally {
                                    session.dispose();
                                }
                            }
                        }
                   
                规则执行环境信息：
                1. 规则代码的包名统一为com.swu.rules
                2. 返回生成的规则代码（.drl文件）
                3. 你回答的时候只需要给出Drools脚本代码即可，以字符串的形式返回，不要有任何其它无关信息，只将代码写成纯字符串返回！注意!这一点非常重要！！！！
                """.formatted(ruleName, ruleDescription);

        String content = chatClient.prompt(new Prompt(prompt)).call().content();
        return content.substring(content.indexOf("package"), content.length() - 3);
    }
} 